package com.gregoiresage.pebble4gopro;

import java.util.Arrays;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.gregoiresage.pebble4gopro.GoProCommand.Device;

public class GoPro {
	
	private final String GOPRO_URL = "http://10.5.5.9:80";
	private final String PASSWORD_URL = GOPRO_URL + "/bacpac/sd";
	private final String CAMERA_DATA_URL = GOPRO_URL + "/camera/sx";

	private final static String BACPAC = "bacpac";
	private final static String CAMERA = "camera";
	private final String COMMAND_URL = GOPRO_URL + "/%s/%s?t=%s&p=%%%02X";
	
	public enum GoProPowerStatus {
		OFF((byte)0x0), 
		IDLE((byte)0x01),
		ON((byte)0x02);
        final public byte value;
        private GoProPowerStatus(byte value) {
                this.value = value;
        }
	}
	
	private String _sPassword = null;
	private GoProPowerStatus _powerStatus = GoProPowerStatus.OFF;
		
	public GoProPowerStatus getPowerStatus(){
		return _powerStatus;
	}
	
	public void connect(){
		byte[] password = sendCommand(PASSWORD_URL);
		if(password != null){
			_sPassword = new String(Arrays.copyOfRange(password, 2, password.length));
			getStatus();
		}
		else {
			_powerStatus = GoProPowerStatus.OFF;
		}
	}
	
	public final byte[] getStatus(){
		byte[] status = sendCommand(CAMERA_DATA_URL + "?t=" + _sPassword);
		if(status != null && status.length == 56){
			_powerStatus = GoProPowerStatus.ON;
		}
		else if(status != null){
			_powerStatus = GoProPowerStatus.IDLE;
		}
		else {
			_powerStatus = GoProPowerStatus.OFF;
		}
		return status;
	}
	
	private final byte[] sendCommand(String url){
		HttpGet httpGet = new HttpGet(url);

		HttpParams httpParameters = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		// The default value is zero, that means the timeout is not used. 
		int timeoutConnection = 500;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT) 
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = 500;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
		try {
			// Execute HTTP Get Request
			return EntityUtils.toByteArray(httpClient.execute(httpGet).getEntity());
		} catch (Exception e) {
			// GoPro off or wifi off
		} 
		return null;
	}
	
	public final byte[] sendCommand(GoProCommand command){
		String url = String.format(COMMAND_URL, command._device == Device.BACPAC ? BACPAC : CAMERA, command._name, _sPassword, command._value);
		return sendCommand(url);
	}
}
